<template>
  <base-load-page :loadState="false" class="base-load-page">
    <template #head>
      <div style="padding-bottom: 15px" class="head-box">
        <div class="left-box">
          <base-date-picker
            v-model="dataRange"
            valueFormat="YYYY-MM-DD"
            format="YYYY-MM-DD"
            type="daterange"
            startPlaceholder="开始日期"
            endPlaceholder="结束日期"
            style="flex-grow: 0; width: 350px"
            clearable
            @change="getAxiosData(true)"
          ></base-date-picker>
          <base-input-search
            v-model="filterData.dramaTitle"
            clearable
            placeholder="请输入剧名"
            style="width: 230px"
            maxlength="30"
            :prefixIcon="IconSearch"
            @submit="getAxiosData(true)"
          ></base-input-search>
          <base-input-search
            v-model="filterData.referralLinkName"
            clearable
            placeholder="请输入充值链接名称"
            style="width: 230px"
            maxlength="30"
            :prefixIcon="IconSearch"
            @submit="getAxiosData(true)"
          ></base-input-search>
<!--          <base-input-search-->
<!--            v-model="filterData.referralLinkId"-->
<!--            clearable-->
<!--            placeholder="请输入充值链接ID"-->
<!--            style="width: 230px"-->
<!--            maxlength="30"-->
<!--            :prefixIcon="IconSearch"-->
<!--            @submit="getAxiosData(true)"-->
<!--          ></base-input-search>-->
<!--                    <bubble-select-local-->
<!--                      v-model="filterData.orderPlatform"-->
<!--                      labelKey="label"-->
<!--                      valueKey="appName"-->
<!--                      :filterable="false"-->
<!--                      style="width: 230px"-->
<!--                      :list="platformList"-->
<!--                      placeholder="请选择小程序平台"-->
<!--                      @change="getAxiosData(true)"-->
<!--                    ></bubble-select-local>-->
          <bubble-select-local
            v-model="filterData.status"
            labelKey="label"
            valueKey="value"
            :filterable="false"
            style="width: 230px"
            :list="[
              { label: '全部', value: '' },
              { label: '异常', value: -1 },
              { label: '待支付', value: 0 },
              { label: '已支付', value: 1 },
              { label: '支付失败', value: 2 },
              { label: '已退款', value: 3 },
              { label: '已关闭', value: 4 },
            ]"
            placeholder="请选择支付状态"
            @change="getAxiosData(true)"
          ></bubble-select-local>
          <base-input-search
            v-model="filterData.outTradeNo"
            clearable
            placeholder="请输入订单号"
            style="width: 230px"
            maxlength="30"
            :prefixIcon="IconSearch"
            @submit="getAxiosData(true)"
          ></base-input-search>
          <base-input-search
            v-model="filterData.userId"
            clearable
            placeholder="请输入用户id"
            style="width: 230px"
            maxlength="30"
            :prefixIcon="IconSearch"
            @submit="getAxiosData(true)"
          ></base-input-search>
          <!--          <bubble-select-local -->
          <!--            v-model="filterData.investmentChannel" -->
          <!--            labelKey="label" -->
          <!--            valueKey="value" -->
          <!--            :filterable="false" -->
          <!--            style="width: 230px" -->
          <!--            :list="[ -->
          <!--              { label: '全部', value: '' }, -->
          <!--              { label: '巨量', value: 'juliang' }, -->
          <!--              { label: '磁力', value: 'cili' }, -->
          <!--              { label: '腾讯', value: 'tengxun' }, -->
          <!--              { label: '星图', value: 'xingtu' }, -->
          <!--            ]" -->
          <!--            placeholder="请选择渠道" -->
          <!--            @change="getAxiosData(true)" -->
          <!--          ></bubble-select-local> -->
          <bubble-select-local
            v-model="filterData.devicePlatform"
            labelKey="label"
            valueKey="value"
            :filterable="false"
            style="width: 230px"
            :list="[
              { label: '全部', value: '' },
              { label: '安卓', value: 'android' },
              { label: '苹果', value: 'ios' },
            ]"
            placeholder="请选择用户设备系统平台"
            @change="getAxiosData(true)"
          ></bubble-select-local>
          <base-input-search
            v-model="filterData.promotionId"
            clearable
            placeholder="请输入广告ID"
            style="width: 230px"
            maxlength="30"
            :prefixIcon="IconSearch"
            @submit="getAxiosData(true)"
          ></base-input-search>
          <!--          <bubble-select-local -->
          <!--            v-model="filterData.isFirstRecharge" -->
          <!--            labelKey="label" -->
          <!--            valueKey="value" -->
          <!--            :filterable="false" -->
          <!--            style="width: 230px" -->
          <!--            :list="[ -->
          <!--              { label: '全部', value: '' }, -->
          <!--              { label: '首充', value: 0 }, -->
          <!--              { label: '复充', value: 1 }, -->
          <!--            ]" -->
          <!--            placeholder="请选择首充/复充" -->
          <!--            @change="getAxiosData(true)" -->
          <!--          ></bubble-select-local> -->
          <!--          <bubble-select-local -->
          <!--            v-model="filterData.iaaFlag" -->
          <!--            labelKey="label" -->
          <!--            valueKey="value" -->
          <!--            :filterable="false" -->
          <!--            style="width: 230px" -->
          <!--            :list="[ -->
          <!--              { label: '全部', value: undefined }, -->
          <!--              { label: '付费', value: 0 }, -->
          <!--              { label: '免费', value: 1 }, -->
          <!--            ]" -->
          <!--            placeholder="请选择推广模式" -->
          <!--            @change="getAxiosData(true)" -->
          <!--          ></bubble-select-local> -->
          <base-input-search
            v-model="filterData.wxFinderId"
            clearable
            placeholder="微信视频号作者Id"
            style="width: 230px"
            maxlength="30"
            :prefixIcon="IconSearch"
            @submit="getAxiosData(true)"
          ></base-input-search>
                    <bubble-select-local
                      v-model="filterData.appCode"
                      labelKey="appName"
                      valueKey="appCode"
                      :filterable="false"
                      style="width: 230px"
                      :list="platformList"
                      placeholder="小程序平台"
                      @change="getAxiosData(true)"
                    ></bubble-select-local>
          <bubble-select-local
            v-model="filterData.wxFinderOrigin"
            labelKey="label"
            valueKey="value"
            :filterable="false"
            style=" display: none;width: 230px"
            :list="[
              { label: '全部', value: '0' },
              { label: '投放', value: '1' },
              { label: '星图', value: '2' },
            ]"
            placeholder="视频号订单来源"
            @change="getAxiosData(true)"
          ></bubble-select-local>
          <!--          <el-button type="primary" @click="clickExport">数据导出</el-button> -->
          <el-button type="primary" @click="clickExportOther">数据导出</el-button>
        </div>
      </div>
    </template>
    <div class="page-content">
      <div class="statistics-block">
        <div v-for="i in statisticsData" :key="i.flag" class="statistics">
          <div class="title">{{ i.name }}</div>
          <div class="value" :class="{ 'operable': i.type === 'primary' }">{{ i.format(censusData) }}</div>
        </div>
      </div>
      <el-table ref="elTableRef" v-loading="baseData.loading" border height="100%" :data="tableData" showOverflowTooltip stripe style="width: 100%">
        <template #empty>
          <base-empty :description="description" :pageLoadButton="[{ text: '重新加载', callBack: () => getAxiosData() }]"></base-empty>
        </template>
        <el-table-column
          fixed
          type="index"
          :index="(index: number) => (filterData.current - 1) * filterData.size + index + 1"
          label="编号"
          sortable
          width="60"
          align="center"
          headerAlign="center"
        ></el-table-column>
        <el-table-column label="用户" fixed prop="nickname" minWidth="180">
          <template #default="{ row }">
            <div class="content-wrap">
              <p>
                昵称:
                <span class="highlighted" @click="clipboard(row.nickname)">{{ row.nickname }}</span>
              </p>
              <p>
                ID:
                <span class="highlighted" @click="clipboard(row.userId)">{{ row.userId }}</span>
              </p>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="注册时间" prop="registerTime" minWidth="180"></el-table-column>
        <el-table-column label="短剧" prop="dramaTitle" minWidth="180"></el-table-column>
        <el-table-column label="充值链接" prop="referralLinkName" minWidth="220">
          <template #default="{ row }">
            <div class="content-wrap">
              <p>
                ID:
                <span class="highlighted" @click="clipboard(row.referralLinkId)">{{ row.referralLinkId }}</span>
              </p>
              <p>
                <span>{{ row.referralLinkName || '-' }}</span>
              </p>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="小程序平台" prop="orderPlatform" minWidth="100">
          <template #default="{ row }">
            <el-tag v-if="row.orderPlatform === 'mp-kuaishou'" key="el-tag-1" size="small">快手</el-tag>
            <el-tag v-else-if="row.orderPlatform === 'mp-toutiao'" key="el-tag-2" type="warning" size="small">抖音</el-tag>
            <el-tag v-else-if="row.orderPlatform === 'mp-weixin'" key="el-tag-3" type="success" size="small">微信</el-tag>
            <el-tag v-else key="el-tag-4" type="danger" size="small">未知</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="订单号" prop="outTradeNo" minWidth="220"></el-table-column>
        <el-table-column label="订单金额" prop="totalAmount" minWidth="130"></el-table-column>
        <el-table-column label="订单类型" prop="orderDetail" minWidth="160">
          <template #default="{ row }">
            {{ orderTypeOptions.find((v) => v.value === row.orderType)?.label || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="首/复冲" prop="isFirstRecharge" minWidth="80">
          <template #default="{ row }">
            {{ row.isFirstRecharge === 0 ? '首充' : row.isFirstRecharge === 1 ? '复冲' : '未知' }}
          </template>
        </el-table-column>
        <el-table-column label="充值次数" prop="referralRechargeCount" minWidth="90"></el-table-column>
        <el-table-column label="订单状态" prop="status" minWidth="100">
          <template #default="{ row }">
            <div v-if="row.status === -1" class="abnormal order-status">异常</div>
            <div v-else-if="row.status === 0" class="order-status pending-payment">待支付</div>
            <div v-else-if="row.status === 1" class="order-status paid">已支付</div>
            <div v-else-if="row.status === 2" class="order-status payment-failed">支付失败</div>
            <div v-else-if="row.status === 3" class="order-status refunded">已退款</div>
            <div v-else-if="row.status === 4" class="closed order-status">已关闭</div>
            <div v-else class="order-status unknown">未知</div>
          </template>
        </el-table-column>
        <el-table-column label="支付渠道" prop="payChannel" minWidth="100">
          <template #default="{ row }">
            {{ orderPayChannelOptions.find((v) => v.value === row.payChannel)?.label || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="订单创建时间" prop="createTime" minWidth="180"></el-table-column>
        <el-table-column label="订单支付时间" prop="tradeTime" minWidth="180"></el-table-column>
        <el-table-column label="广告ID" prop="promotionId" minWidth="180"></el-table-column>
        <el-table-column label="用户设备系统平台" prop="devicePlatform" minWidth="150">
          <template #default="{ row }">
            <div v-if="row.devicePlatform === 'ios'">苹果</div>
            <div v-else-if="row.devicePlatform === 'android'">安卓</div>
          </template>
        </el-table-column>
        <el-table-column label="回传状态" prop="reportBackStatus" minWidth="90">
          <template #default="{ row }">
            <el-tag v-if="row.reportBackStatus === 0" key="el-tag-1" size="small">无需上报</el-tag>
            <el-tag v-else-if="row.reportBackStatus === 1" key="el-tag-2" type="success" size="small">上报成功</el-tag>
            <el-tag v-else-if="row.reportBackStatus === 2" key="el-tag-3" type="danger" size="small">上报失败</el-tag>
            <el-tag v-else key="el-tag-4" type="danger" size="small">未知</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="回传操作" prop="reportBackStatus" minWidth="90">
          <template #default="{ row }">
            <div style="display: flex; flex-direction: column; gap: 4px; overflow: hidden">
              <el-button
                v-if="row.reportBackStatus !== 1 && row.status === 1"
                link
                type="primary"
                size="small"
                :loading="row.__syncBackLoading"
                :disabled="row.back === 0"
                style="margin-left: 0"
                :icon="EpMostlyCloudy"
                @click="handleSyncBack(row)"
              >
                手动回传
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <template #foot>
      <div class="pagination-box">
        <el-pagination
          v-model:currentPage="filterData.current"
          v-model:pageSize="filterData.size"
          :pageSizes="[20, 30, 40, 50]"
          :disabled="baseData.loading"
          :pagerCount="13"
          layout="total, prev, pager, next, sizes, jumper"
          :total="baseData.total"
          @change="getAxiosData(true)"
        ></el-pagination>
      </div>
    </template>
  </base-load-page>
</template>

<script setup lang="ts">
  import IconSearch from '~icons/ep/search';
  import EpMostlyCloudy from '~icons/ep/mostly-cloudy';
  import {
    type AppUserSavings,
    type AppUserSavingsListRequest,
    getAppUserStarListAxios,
    getOrderTotalPriceAxios,
    getStarOrderTotalPriceAxios,
    orderExportMonthVideoData,
    orderPayChannelOptions,
    orderTypeOptions,
    socialList,
    getWechatPlatformList, WechatPlatformList,
  } from '@/api/app-user-management';
  import { formatNumberWithMoney } from '@/utils/numb.ts';
  import { easeDownloadFile } from '@/utils/common.ts';
  import { blobToString } from '@/utils/data.ts';

  const { proxy } = getCurrentInstance() as any;
  import { useClipboardHelper } from '@/utils/useClipboard.ts';
  import { reportOrderBackAxios } from '@/api/marketing-management';

  const elTableRef: $RefComp<'ElTable'> = ref(null);
  const baseData = shallowReactive({
    type: 'add' as 'add' | 'edit',
    /** 加载状态 */
    loading: true,
    /** 总数量 */
    total: 0,
  });


  const dataRange = ref<[string, string] | undefined>();
  const filterData: Ref<AppUserSavingsListRequest> = ref<AppUserSavingsListRequest>({
    orderPlatform: undefined,
    outTradeNo: '',
    payChannel: '',
    status: '',
    dramaTitle: '',
    startDate: '',
    endDate: '',
    referralLinkName: '',
    referralLinkId: '',
    isFirstRecharge: '',
    promotionId: '',
    userId: '',
    investmentChannel: undefined,
    current: 1,
    size: 40,
    devicePlatform: '',
    iaaFlag: undefined,
    wxFinderId: undefined,
    wxFinderFlag: undefined,
    appCode: undefined,
    wxFinderOrigin: 2,
  });

  const tableData: Ref<AppUserSavings[]> = ref([]);
  const description = ref('');

  const appCodeList = ref();

  const platformList = ref<WechatPlatformList>([]);


  /** 平台类型 */
  const getsocialList = async () => {
    const res = await socialList();
    appCodeList.value = res.data;
  };


  const getPlatformList=async ()=>{
    let callback = await getWechatPlatformList();
    platformList.value = callback.data || [];
  }

  onMounted(() => {
    dataRange.value = [proxy.$dayjs().format('YYYY-MM-DD'), proxy.$dayjs().format('YYYY-MM-DD')];
    getAxiosData();
    getsocialList();
    getPlatformList();
  });

  /** 统计数据 */
  const censusData = ref<Record<string, number>>({
    priceAll: 0,
    orderNum: 0,
  });

  /**
   * 设置表格数据
   */
  async function getAxiosData(showLoading = true) {
    if (Array.isArray(dataRange.value) && dataRange.value.length) {
      filterData.value.startDate = `${dataRange.value[0]} 00:00:00`;
      filterData.value.endDate = `${dataRange.value[1]} 23:59:59`;
    } else {
      filterData.value.startDate = '';
      filterData.value.endDate = '';
    }
    try {
      await nextTick();
      baseData.loading = Boolean(showLoading);
      const res = await Promise.all([getAppUserStarListAxios(filterData.value), getStarOrderTotalPriceAxios(filterData.value)]);
      censusData.value.priceAll = res[1].data.totalAmount;
      censusData.value.orderNum = res[1].data.orderNum;
      tableData.value = res[0].data.records;
      description.value = '暂无数据';
      filterData.value.current = res[0].data.current;
      filterData.value.size = res[0].data.size;
      baseData.total = res[0].data.total;
      baseData.loading = false;
    } catch (error) {
      baseData.loading = false;
      tableData.value = [];
      description.value = error.msg || '加载失败，-BD001';
    }
  }

  interface StatisticsItem {
    name: string;
    flag: 'orderNum' | 'priceAll';
    type?: string;
    format: (val: Record<'orderNum' | 'priceAll', number>) => number | string;
  }

  const statisticsData = ref<StatisticsItem[]>([
    {
      name: '订单总金额',
      flag: 'priceAll',
      format(val) {
        return formatNumberWithMoney(val?.priceAll || 0) ?? 0;
      },
    },
    {
      name: '订单总笔数',
      flag: 'orderNum',
      format(val) {
        return formatNumberWithMoney(val?.orderNum || 0) ?? 0;
      },
    },
  ]);

  /** 数据导出 */
  // const clickExport = async () => {
  //   const res = await orderListExport(filterData.value);
  //   console.log('res', res);
  //   easeDownloadFile(res, '订单列表数据');
  // };

  /** 星图数据导出 */
  const clickExportOther = async () => {
    try {
      const res = await orderExportMonthVideoData({
        startDate: filterData.value.startDate,
        endDate: filterData.value.endDate,
        appCode: filterData.value.appCode,
      });

      const blobStr = await blobToString(res);
      if (blobStr.indexOf('code') !== -1) {
        const callback = JSON.parse(blobStr);
        if (!callback.code) {
          ElToast.error(callback.msg || `导出失败`);
        }
      } else {
        easeDownloadFile(res, '星图视频数据');
      }
    } catch (e) {}
  };

  /** 校正消耗 */
  async function handleSyncBack(row: AppUserSavings) {
    try {
      row.__syncBackLoading = true;
      await reportOrderBackAxios(row.orderId!);
      row.__syncBackLoading = false;
      ElToast.success('回传成功');
      getAxiosData(false);
    } catch (error) {
      row.__syncBackLoading = false;
      ElToast.error(error.msg || `回传失败，-BD004`);
    }
  }
  const { copyClipboard } = useClipboardHelper();

  /** 复制 */
  function clipboard(text: string) {
    copyClipboard(text);
  }
</script>

<style lang="scss" scoped>
  .pagination-box {
    @include flex(row, nowrap, center, center, center);
    padding-top: 15px;
  }

  .head-box {
    @include flex(row, nowrap, flex-start, center, center);

    .left-box {
      // display: grid;
      display: flex;
      flex: 1;
      flex-wrap: wrap;
      // grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
      // grid-gap: 15px;
      gap: 14px;
      margin-right: 15px;
    }
  }

  .page-content {
    display: flex;
    flex-direction: column;
    height: 100%;
  }

  .order-status {
    box-sizing: border-box;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    height: 20px;
    padding: 0 7px;
    font-size: 12px;
    line-height: 12px;
    color: #ffffff;
    border-radius: 5px;

    /* 异常状态 */
    &.abnormal {
      color: var(--el-color-danger);
      background-color: var(--el-color-danger-light-9);
      border: 1px solid var(--el-color-danger-light-5);
    }

    /* 待支付状态 */
    &.pending-payment {
      color: var(--el-color-warning);
      background-color: var(--el-color-warning-light-9);
      border: 1px solid var(--el-color-warning-light-8);
    }

    /* 已支付状态 */
    &.paid {
      color: var(--el-color-success);
      background-color: var(--el-color-success-light-9);
      border: 1px solid var(--el-color-success-light-8);
    }

    /* 支付失败状态 */
    &.payment-failed {
      color: var(--el-color-danger);
      background-color: var(--el-color-danger-light-9);
      border: 1px solid var(--el-color-danger-light-8);
    }

    /* 已退款状态 */
    &.refunded {
      color: var(--el-color-violet);
      background-color: var(--el-color-violet-light-9);
      border: 1px solid var(--el-color-violet-light-8);
    }

    /* 已关闭状态 */
    &.closed {
      color: var(--el-color-info);
      background-color: var(--el-color-info-light-9);
      border: 1px solid var(--el-color-info-light-8);
    }

    /* 未知状态 */
    &.unknown {
      color: var(--el-color-cyan);
      background-color: var(--el-color-cyan-light-9);
      border: 1px solid var(--el-color-cyan-light-8);
    }
  }

  .content-wrap {
    white-space: wrap;
  }
</style>
